//
//  Client.m
//  XXX
//
//  Created by Xiaoshiheng_pro on 2017/2/18.
//  Copyright © 2017年 Xiaoshiheng_pro. All rights reserved.
//



#import "Client.h"
@interface Client()<GCDAsyncSocketDelegate>

@end

@implementation Client

+ (instancetype)ClientInit{
    static Client* ClientMode;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        ClientMode = [[Client alloc] init];
        //1、初始化
        ClientMode.clinetSocke = [[GCDAsyncSocket alloc] initWithDelegate:ClientMode delegateQueue:dispatch_get_main_queue()];
        
        
    });
    return ClientMode;
}

- (void)startConnectToHost:(NSString *)serverUrl{
    
    //2、连接服务器
    [self.clinetSocke connectToHost:serverUrl onPort:[@"8080" integerValue] withTimeout:-1 error:nil];
}


#pragma mark - GCDAsynSocket Delegate

///建立连接
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
    
    /* 开始从 socket 中读取字节流 */
    // P.S. 每次收到回调后立即读取数据会断开连接，所以采用延迟一秒后再读数据
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSUInteger length = sizeof(NSUInteger);
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocke readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:HEADER_TAG];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(clientSocket:didConnectToHost:port:)]) {
            
            [self.delegate clientSocket:sock didConnectToHost:host port:port];
        }
    });
    

}
///失去连接
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(clientSocketDidDisconnect:withError:)]) {
        
        [self.delegate clientSocketDidDisconnect:sock withError:err];
    }
}

///读取接收长度
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
    
//    NSLog(@"%lu",partialLength);
    
}
///发送进度
- (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
    
}
//收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    
//    NSLog(@"%s", __PRETTY_FUNCTION__);
    if (HEADER_TAG == tag)
    {
        NSUInteger length = 0;
        [data getBytes:&length length:sizeof(NSUInteger)];
        
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocke readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:BODY_TAG];
    }
    else if (BODY_TAG == tag)
    {
        
        NSUInteger length = sizeof(NSUInteger);
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocke readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:HEADER_TAG];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(clientSocket:didReadData:withTag:)]){
            
            [self.delegate clientSocket:sock didReadData:data withTag:tag];
        }
    }
    
}
//发送消息成功
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
//    NSLog(@"发送成功%ld",tag);
    if(self.delegate && [self.delegate respondsToSelector:@selector(clientSocket:didWriteDataWithTag:)]){
        
        [self.delegate clientSocket:sock didWriteDataWithTag:tag];
    }

}

@end
